#! /usr/bin/python3
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
	raise Exception("不支持从这里调用")

__version__ = "1.0"
__all__ = []

from uuid import uuid4

from com.mousechsh.business.lib.MouseChshAuthorizationAnnotition import MouseChshRemoteAuthorizationAnnotition
from com.mousechsh.business.lib.model.MouseChshDomainModel import MouseChshDomainModel
from com.mousechsh.business.lib.model.MouseChshKeyValueModel import MouseChshKeyValueModel
from com.mousechsh.common.data.MouseChshDao import MouseChshDao
from com.mousechsh.common.data.MouseChshData import mousechsh_data_merge
from com.mousechsh.common.data.json.MouseChshJson import mousechsh_json_to_json
from com.mousechsh.common.io.db.MouseChshPostgresql import MouseChshPostgresql
from com.mousechsh.common.middle.http.MouseChshHttpHeader import mousechsh_http_header_accept_language_annotation
from com.mousechsh.common.middle.rest_api.MouseChshRestApi import mousechsh_rest_api_annotation
from com.mousechsh.common.middle.router.MouseChshCorsAnnotition import mousechsh_cors_annotation
from com.mousechsh.common.middle.router.MouseChshHttpRouter import mousechsh_http_router_annotation
from com.mousechsh.common.util.MouseChshDateTime import MouseChshDateTime


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/domain/add')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _addDomain(params):
	lang = params.get('lang', 'zh-cn')
	domain = MouseChshDomainModel()
	domain.set_data(params)
	domain.Id = str(uuid4()).upper()
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   INSERT INTO "A_AD"."T_Domain"(
		   "C_Id",
		   "C_CrOn",
		   "C_MoOn",
		   "L_Scheme",
		   "X_Data",
		   "C_Name",
		   "X_Display",
		   "L_DomainType",
		   "L_Parent_Id"
	   )VALUES(
		   %(id)s,
		   %(cron)s,
		   %(moon)s,
		   'Domain',
		   '{}',
		   %(name)s,
		   %(display)s,
		   %(type)s,
		   %(parent)s
	   )
		   ''', {
			'id': domain.get('Id'),
			'cron': MouseChshDateTime().to_timestamp(),
			'moon': MouseChshDateTime().to_timestamp(),
			'name': domain.get('Name'),
			'domain': domain.get('Domain'),
			'display': mousechsh_json_to_json(
				{
					lang: domain.get('Display'),
					'': lang
				}
			),
			'type': domain.get('Type'),
			'parent': domain.get('Parent')
		}
	)
	db.commit()
	db.close()
	return domain.get('Id')


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/domain/remove')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _removeDomain(params):
	domain = MouseChshDomainModel()
	domain.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   DELETE FROM "A_AD"."T_Domain"
	   WHERE "C_Id" = %(id)s
		   ''', {
			'id': domain.get('Id')
		}
	)
	db.commit()
	db.close()
	return True


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/domain/update')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _updateDomain(params):
	lang = params.get('lang', 'zh-cn')
	domain = MouseChshDomainModel()
	domain.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   "C_Id",
		   "C_CrOn",
		   "C_CrBy",
		   "C_MoOn",
		   "C_MoBy",
		   "C_RvOn",
		   "C_RvBy",
		   "C_St",
		   "C_Owner",
		   "C_Flag",
		   "L_Scheme",
		   "X_Data",
		   "X_Property",
		   "C_Name",
		   COALESCE( "X_Display" ->> %(lang)s, "X_Display" ->> ( "X_Display" ->> '' ) ) AS "C_Display",
		   "L_DomainType" AS "C_DomainType",
		   "L_Parent_Id"
	   FROM "A_AD"."T_Domain"
	   WHERE "C_Id" = %(id)s
		   ''', {
			'lang': lang,
			'id': domain.get('Id')
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshDomainModel)
	domains = dao.parse(data)
	if len(domains) <= 0:
		return
	domain = mousechsh_data_merge(domains[0], domain)
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   UPDATE "A_AD"."T_Domain" SET
		   "C_MoOn"       = %(moon)s,
		   "L_Scheme"     = 'Domain',
		   "X_Data"       = '{}',
		   "C_Name"       = %(name)s,
		   "X_Display"    = "X_Display" || %(display)s,
		   "L_DomainType" = %(type)s,
		   "L_Parent_Id"  = %(parent)s
	   WHERE "C_Id"       = %(id)s
		   ''', {
			'moon': MouseChshDateTime().to_timestamp(),
			'name': domain.get('Name'),
			'domain': domain.get('Domain'),
			'display': mousechsh_json_to_json(
				{
					lang: domain.get('Display').get(lang, None) if isinstance(
						domain.get('Display'), dict
					) else domain.get('Display'),
					'': lang
				}
			),
			'type': domain.get('Type'),
			'parent': domain.get('Parent'),
			'id': domain.get('Id')
		}
	)
	db.commit()
	db.close()
	return domain.get('Id')


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/domain/get')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _getDomain(params):
	lang = params.get('lang', 'zh-cn')
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   A."C_Id",
		   A."C_CrOn",
		   A."C_CrBy",
		   A."C_MoOn",
		   A."C_MoBy",
		   A."C_RvOn",
		   A."C_RvBy",
		   A."C_St",
		   A."C_Owner",
		   A."C_Flag",
		   A."L_Scheme",
		   A."X_Data",
		   A."X_Property",
		   A."C_Name",
		   A."L_DomainType" AS "C_DomainType",
		   A."L_DomainType" AS "L_DomainType_Key",
		   COALESCE( B."X_Display" ->> %(lang)s, B."X_Display" ->> ( B."X_Display" ->> '' ) ) AS "L_DomainType_Display",
		   COALESCE( A."X_Display" ->> %(lang)s, A."X_Display" ->> ( A."X_Display" ->> '' ) ) AS "C_Display",
		   A."X_Display",
		   A."L_Parent_Id"
	   FROM "A_AD"."T_Domain" A
	   LEFT OUTER JOIN "A_Const"."W_KeyValue" B
		   ON A."L_DomainType" = B."C_Key"
	   ORDER BY A."C_Order" ASC
	   LIMIT 100
		   ''', {
			'lang': lang
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshDomainModel)
	dao.set_extra_model(MouseChshKeyValueModel, key='DomainType')
	domains = dao.parse(data)
	return domains
